package com.fire.control.system.support.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fire.control.system.statics.Key;
import com.xdao.framework.persistence.utils.JSON;

public class HttpUtil {

	private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
	
	/**
	 * 设置cookie
	 * @param response
	 * @param name  cookie名字
	 * @param value cookie值
	 * @param maxAge cookie生命周期  以秒为单位
	 */
	public static void addCookie(HttpServletResponse response,String name,String value,int maxAge){
	    Cookie cookie = new Cookie(name,value);
	    cookie.setPath("/");
	    if(maxAge>0)  cookie.setMaxAge(maxAge);
	    response.addCookie(cookie);
	}
	
	/**
	 * 根据名字获取cookie
	 * @param name cookie名字
	 * @return
	 */
	public static Cookie getCookieByName(HttpServletRequest request,String name){
	    Map<String,Cookie> cookieMap = ReadCookieMap(request);
	    if(cookieMap.containsKey(name)){
	        Cookie cookie = (Cookie)cookieMap.get(name);
	        return cookie;
	    }else{
	        return null;
	    }   
	}
	
	/**
	 * 根据名字获取cookie value
	 * @param name cookie名字
	 * @return
	 */
	public static String getCookieValueByName(HttpServletRequest request,String name){
		Cookie cookie = getCookieByName(request,name);
		if(cookie!=null){
			String val = cookie.getValue();
			try {
				return URLDecoder.decode(val,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}return null;
	}
	
	/**
	 * 将cookie封装到Map里面
	 * @param request
	 * @return
	 */
	private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		return cookieMap;
	}
	
	private static void output(HttpServletResponse response,String contentType,Object object) {
		/**过滤器已设置,此处不需要设置*/
		response.setCharacterEncoding("UTF-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Content-Type", contentType+";charset=UTF-8");
		response.setDateHeader("expires", -1);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		response.setHeader(Key.authorization.toString(), "");
 		try {
 			PrintWriter pw = response.getWriter();
 			pw.print(object);
 			pw.flush();
 			pw.close();
 		} catch (IOException e) {
 			logger.info("输出信息出错：" + e);
 		}
 	 }
	 
	 public static void outputJson(HttpServletResponse response,Object object) {
		 output(response,"application/json", JSON.toString(object));
 	 }
	 
	 public static void outputText(HttpServletResponse response,Object object) {
		 output(response,"text/html", object);
 	 }
	 
	 /**  
     * 方法说明 :通过获取所有参数名的方式 
     */   
    @SuppressWarnings({ "rawtypes", "unchecked" })  
    private String getParamNames(HttpServletRequest request) {    
        Map map = new HashMap();    
        Enumeration paramNames = request.getParameterNames();    
        while (paramNames.hasMoreElements()) {    
            String paramName = (String) paramNames.nextElement();    
    
            String[] paramValues = request.getParameterValues(paramName);    
            if (paramValues.length == 1) {    
                String paramValue = paramValues[0];    
                if (paramValue.length() != 0) {    
                    map.put(paramName, paramValue);    
                }    
            }    
        }    
    
        Set<Map.Entry<String, String>> set = map.entrySet();    
        String text = "";  
        for (Map.Entry entry : set) {    
            logger.info(entry.getKey() + ":" + entry.getValue());    
            text += entry.getKey() + ":" + entry.getValue();  
            logger.info("text------->"+text);  
        }    
        if(text.startsWith("[") && text.endsWith("]")){  
            return text;  
        }  
        return "";  
    }  
    
    /**  
     * 方法说明 :通过获取map的方式 
     */   
    @SuppressWarnings("rawtypes")  
    private String getParameterMap(HttpServletRequest request) {  
        Map map = request.getParameterMap();  
        String text = "";  
        if (map != null) {  
            Set set = map.entrySet();  
            Iterator iterator = set.iterator();  
            while (iterator.hasNext()) {  
                Map.Entry entry = (Entry) iterator.next();  
                if (entry.getValue() instanceof String[]) {  
                    logger.info("==A==entry的key： " + entry.getKey());  
                    String key = (String) entry.getKey();  
                    if (key != null && !"id".equals(key) && key.startsWith("[") && key.endsWith("]")) {  
                        text = (String) entry.getKey();  
                        break;  
                    }  
                    String[] values = (String[]) entry.getValue();  
                    for (int i = 0; i < values.length; i++) {  
                        logger.info("==B==entry的value: " + values[i]);  
                        key += "="+values[i];  
                    }  
                    if (key.startsWith("[") && key.endsWith("]")) {  
                        text = (String) entry.getKey();  
                        break;  
                    }  
                } else if (entry.getValue() instanceof String) {  
                    logger.info("==========entry的key： " + entry.getKey());  
                    logger.info("==========entry的value: " + entry.getValue());  
                }  
            }  
        }  
        return text;  
    }  
    
    /*** 
     * 获取 request 中 json 字符串的内容 
     *  
     * @param request 
     * @return : <code>byte[]</code> 
     * @throws IOException 
     */  
    public static String getRequestJsonString(HttpServletRequest request)  
            throws IOException {  
        String submitMehtod = request.getMethod();  
        // GET  
        if (submitMehtod.equals("GET")) {  
            return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");  
        // POST  
        } else {  
            return getRequestPostStr(request);  
        }  
    }  
  
    /**       
     * 描述:获取 post 请求的 byte[] 数组 
     * <pre> 
     * 举例： 
     * </pre> 
     * @param request 
     * @return 
     * @throws IOException       
     */  
    public static byte[] getRequestPostBytes(HttpServletRequest request)  
            throws IOException {  
        int contentLength = request.getContentLength();  
        if(contentLength<0){  
            return null;  
        }  
        byte buffer[] = new byte[contentLength];  
        for (int i = 0; i < contentLength;) {  
  
            int readlen = request.getInputStream().read(buffer, i,  
                    contentLength - i);  
            if (readlen == -1) {  
                break;  
            }  
            i += readlen;  
        }  
        return buffer;  
    }  
  
    /**       
     * 描述:获取 post 请求内容 
     * <pre> 
     * 举例： 
     * </pre> 
     * @param request 
     * @return 
     * @throws IOException       
     */  
    public static String getRequestPostStr(HttpServletRequest request)  
            throws IOException {  
        byte buffer[] = getRequestPostBytes(request);  
        String charEncoding = request.getCharacterEncoding();  
        if (charEncoding == null) {  
            charEncoding = "UTF-8";  
        }  
        return new String(buffer, charEncoding);  
    }  
    
    public static Map<String, Object> getRequestJsonStringToMap(HttpServletRequest request){
    	Map<String, Object> map = new HashMap<String, Object>();
		try {
			String str = getRequestPostStr(request);
			if(StringUtils.isNotEmpty(str)){
				str = str.replaceAll("\"", "'");
				System.out.println("-------------"+str);
				map = JSONUtil.toMap(str);
				System.out.println("-------------"+map.get("userId"));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
    	return map;
    }
    
    
	
}
